<template>
  <div class="toolbar-wrapper">
    <div class="default-toolbar">
      <slot name="toolbar" :activateTool="toolHandler" :activeTool="activeTool">
        <!-- 默认工具栏 -->
        <div v-for="tool in combinedTools" :key="tool.name" class="tool-item" @click="toolHandler(tool)"
          :class="{ active: activeTool === tool.name }">
          <!-- 使用i标签应用图标类 -->
          <i :class="tool.icon"></i>
          <span class="tool-title">{{ tool.label }}</span>
        </div>
      </slot>
    </div>
  </div>
</template>

<script lang="ts">

import { Component, Vue, Prop } from 'vue-property-decorator';
import { defaultLocation } from '@/utils/amap-helper';
import {
  getDefaultOverlayName, getTypeName, getTypeTagClass,
  formatPosition,
  formatRadius,
  formatArea,
  calculateCircleArea,
  getArea,
  formatLength,
  calculatePolygonCenter
} from '@/config/mapFunction';

declare const AMap: any;
// 定义圆形对象和文本的接口
@Component
export default class Toolbar extends Vue {
  @Prop({ default: () => [] }) defaultTools;
  @Prop() map: any;
  @Prop() fixedTools;
  private activeTool: string | null = null;
  mouseTool: any;
  overlays: any = [];
  features: any[] = [];
  private isEditing = false;
  private editors: any[] = []; // 用于存储编辑器实例
  // 使用数组存储所有圆形对象及其对应的文本
  // 创建半径显示控件
  get combinedTools() {
    return [
      ...this.defaultTools,
      ...this.fixedTools.filter(t => t.visible)
    ];
  }

  drawMouseTool(type) {
    switch (type) {
      case 'marker': {
        this.mouseTool.marker({
          //同Marker的Option设置
          icon: new AMap.Icon({
            image: defaultLocation,
            size: new AMap.Size(32, 32),
            anchor: 'center',

          }),
        });
        break;
      }
      case 'polyline': {
        this.mouseTool.polyline({
          strokeColor: '#80d8ff'
          //同Polyline的Option设置
        });
        break;
      }
      case 'polygon': {
        this.mouseTool.polygon({
          fillColor: '#00b0ff',
          strokeColor: '#80d8ff'
          //同Polygon的Option设置
        });
        break;
      }
      case 'rectangle': {
        this.mouseTool.rectangle({
          fillColor: '#00b0ff',
          strokeColor: '#80d8ff'
          //同Polygon的Option设置
        });
        break;
      }
      case 'circle': {
        // 清除现有资源和事件
        // 重置鼠标工具状态
        if (this.mouseTool && typeof this.mouseTool.close === 'function') {
          this.mouseTool.close();
        }
        // 创建圆形工具
        this.mouseTool.circle({
          fillColor: '#00b0ff',
          strokeColor: '#80d8ff',
          draggable: true,
          radius: 1000, //半径
          cursor: 'move',
          editable: true
        });
        break;
      }
      case 'clean': {
        this.cleanOverlays()
        break;
      }
      case 'startEdit': {
        this.startEdit();
        break;
      }
      case 'cancelEdit': {
        this.isEditing = false;
        this.cancelEdit();
        break;
      }
    }
  }

  toolHandler(tool) {
    this.drawMouseTool(tool.name);
    const hasFix = this.fixedTools.find(t => t.name === tool.name);
    if (!hasFix) {
      this.$emit('tool-change', tool);
    }
  }
  // 修改拖拽事件处理方法，支持多个圆形
  addDragEvents(obj) {
    if (obj && obj.setOptions) {
      obj.setOptions({ draggable: true });

      // 拖拽开始事件
      obj.on('dragstart', () => {
        console.log('开始拖拽');
      });

      // 拖拽结束事件 - 更新半径文本
      obj.on('dragend', () => {
        console.log('拖拽结束');
        this.parseFreatureData(obj);
        this.$emit('draw-overlay', obj);
      });
      // 圆形变化事件 - 实时更新半径文本
    }
  }

  mounted() {

    AMap.plugin(['AMap.MouseTool'], () => { //异步加载插件
      this.mouseTool = new AMap.MouseTool(this.map);
      this.$message.info('工具栏加载完成');

      // 全局绘制事件监听
      this.mouseTool.on('draw', e => {
        if (e.obj) {
          // 将所有绘制的图形添加到overlays数组
          this.addOverlay(e.obj);
          e.obj.setOptions({ draggable: true });
          // 触发事件通知父组件
          this.$emit('shape-drawn', {
            type: e.obj.CLASS_NAME,
            obj: e.obj
          });
          this.addDragEvents(e.obj);
          // 如果是圆形，创建文本标记

          if (e.obj.CLASS_NAME === 'Overlay.Circle') {

            this.createRadiusTextForCircle(e.obj);

          }
          // 关闭绘图工具（一次只绘制一个）
          this.mouseTool.close();
        }
      });
    });
  }

  addOverlay(overlay: any, prop?: any) {
    // Add overlay to collection 
    // Determine default name based on overlay type 
    const name = getDefaultOverlayName(overlay);
    const cls = overlay.CLASS_NAME;
    // Set overlay metadata 
    overlay.extData = {
      id: `vector-${Date.now()}`,
      name: prop?.name || name,  // Use prop.name  if exists, otherwise use default 
      type: cls,
      typeName: getTypeName(cls),
      style: getTypeTagClass(cls),
      ...(prop?.category && { category: prop.category }), // Conditionally add category 
    };
    this.parseFreatureData(overlay);
    this.overlays.push(overlay);
    // Update store 
    this.$store.dispatch('setFeatures', this.overlays);
  }

  private createRadiusTextForCircle(circle: any) {

      // 创建文本标记

      const text = new AMap.Text({

      text: this.getCircleRadiusText(circle),

      position: circle.getCenter(),

      anchor: 'center', // 居中

      style: {

      'background-color': 'rgba(255,255,255,0.7)',

      'border': '1px solid #1890ff',

      'padding': '2px 5px',

      'border-radius': '3px',

      'font-size': '12px'

      }

      });

      text.setMap(this.map);

      // 将文本标记与圆形关联
      circle.extData.radiusText = text;
}

private getCircleRadiusText(circle: any): string {

  const radius = circle.getRadius();

  return formatRadius(radius);

}
  // 组件销毁前清理资源
  beforeDestroy() {
    try {
      // 清理鼠标工具
      this.mouseTool?.close(true);
      // 清理所有编辑器
      this.closeAllEditors();
    } catch (error) {
      console.error("组件销毁时清理资源出错:", error);
    }
  }

  // 关闭所有编辑器
  private closeAllEditors() {
    this.editors.forEach(editor => {
      if (editor && typeof editor.close === 'function') {
        editor.close();
      }
    });
    this.editors = [];
  }


  startEdit() {
    this.isEditing = true;
    this.activeTool = 'startEdit';

    // 先关闭所有之前的编辑器
    this.closeAllEditors();

    // 遍历所有覆盖物，为每个覆盖物创建对应的编辑器
    this.overlays.forEach((obj: any) => {
      if (!obj) return;

      try {
        const className = obj.CLASS_NAME;

        if (className === 'Overlay.Circle') {
          // 圆形使用 CircleEditor
          AMap.plugin(['AMap.CircleEditor'], () => {
            const editor = new AMap.CircleEditor(this.map, obj);
            editor.open();
            editor.on('adjust', () => {
              this.parseFreatureData(obj);
            });
            this.editors.push(editor);
          });
        } else if (className === 'Overlay.Polygon') {
          // 多边形使用 PolyEditor
          AMap.plugin(['AMap.PolyEditor'], () => {
            const editor = new AMap.PolyEditor(this.map, obj);
            editor.open();
            editor.on('adjust', () => {
              this.parseFreatureData(obj);
            });
            this.editors.push(editor);
          });
        } else if (className === 'Overlay.Rectangle') {
          // 矩形使用 PolyEditor（矩形是特殊的多边形）
          AMap.plugin(['AMap.RectangleEditor'], () => {
            const editor = new AMap.RectangleEditor(this.map, obj);
            editor.open();
            editor.on('adjust', () => {
              this.parseFreatureData(obj);
            });
            this.editors.push(editor);
          });
        } else if (className === 'Overlay.Polyline') {
          // 折线使用 PolyEditor
          AMap.plugin(['AMap.PolyEditor'], () => {
            const editor = new AMap.PolyEditor(this.map, obj);
            editor.open();
            editor.on('adjust', () => {
              this.parseFreatureData(obj);
            });
            this.editors.push(editor);
          });
        }
      } catch (error) {
        console.error("启用编辑失败:", error);
      }
    });

    // 更新固定工具按钮状态
    this.$emit('edit-mode-changed', true);
    this.$message.success('已进入编辑模式');
  }

  // 清除所有覆盖物
  removeOverlay(overlay) {
    if (overlay) {
      if(!overlay.getExtData().category){
          this.map.remove(overlay);
      }
      // 移除文本标记

      if (overlay.extData && overlay.extData.radiusText) {
          this.map.remove(overlay.extData.radiusText);
      }
      const index = this.overlays.indexOf(overlay);
      if (index !== -1) {
        this.overlays.splice(index, 1);
      }
      this.$store.dispatch('setFeatures', this.overlays);
    }
  }


  parseFreatureData(feature: any): string[] {
    const type = feature.extData.type;
    const props: string[] = [];
    const category = feature.extData.category;
    switch (type) {
      case 'AMap.Marker':
        feature.extData.location = formatPosition(feature.getPosition());
        break;
      case 'Overlay.Circle':
        feature.extData.radius = formatRadius(feature.getRadius());
        feature.extData.center = formatPosition(feature.getCenter());
        feature.extData.area = formatArea(calculateCircleArea(feature.getRadius()));
        // 更新文本标记

          if (feature.extData.radiusText) {
            feature.extData.radiusText.setText(this.getCircleRadiusText(feature));
            feature.extData.radiusText.setPosition(feature.getCenter());

          }
        break;
      case 'AMap.Polygon':
      case 'Overlay.Polygon': {
        const path = feature.getPath();
        if (category) {
          feature.extData.area = formatArea(getArea(path[0]));
          feature.extData.center = formatPosition(calculatePolygonCenter(path[0]));
        } else {
          feature.extData.area = formatArea(getArea(path));
          feature.extData.center = formatPosition(calculatePolygonCenter(path));
        }
        break;
      }

      case 'Overlay.Rectangle': {
        const bounds = feature.getBounds();
        const southWest = bounds.getSouthWest();
        const northEast = bounds.getNorthEast();
        // 计算矩形中心点
        const center = new AMap.LngLat(
          (southWest.lng + northEast.lng) / 2,
          (southWest.lat + northEast.lat) / 2
        );
        feature.extData.center = formatPosition(center);
        feature.extData.width = formatLength(AMap.GeometryUtil.distance(southWest, new AMap.LngLat(northEast.lng, southWest.lat)));
        feature.extData.height = formatLength(AMap.GeometryUtil.distance(southWest, new AMap.LngLat(southWest.lng, northEast.lat)));
        break;
      }
      case 'Overlay.Polyline':
        feature.extData.lineLength = formatLength(AMap.GeometryUtil.distance(feature.getPath()));
        break;
    }

    return props;
  }


  // 清除所有覆盖物
  private cleanOverlays() {
    // 先关闭所有编辑器
    this.closeAllEditors();

    // 然后移除所有覆盖物
    this.overlays.forEach((overlay: any) => {
      if (overlay && typeof overlay.remove === 'function') {
        // 移除关联的文本标记

          if (overlay.extData && overlay.extData.radiusText) {
            this.map.remove(overlay.extData.radiusText);
          }
          this.map.remove(overlay);
      }
    });
    this.overlays = [];
    this.$store.dispatch('setFeatures', this.overlays);
    this.$emit('overlays-cleared');
    this.mouseTool.close(true)
  }
  // 取消编辑方法 
  cancelEdit() {
    this.isEditing = false;
    this.activeTool = null;

    // 关闭所有编辑器
    this.closeAllEditors();

    // 更新固定工具按钮状态
    this.$emit('edit-mode-changed', false);
    this.$message.info('已退出编辑模式');
  }
} 
</script>

<style scoped>
.control-group.bottom-right {
  position: fixed;
  bottom: 1px;
  right: 0px;
}

.search-box {
  display: flex;
  gap: 8px;
}

.toolbar-wrapper {
  display: flex;
  gap: 8px;
  height: 32px;
}

button {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
}

button:hover {
  background: #f0f0f0;
}

button.active {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.overlay-container {
  position: absolute;
  /* 改为fixed定位 */
  z-index: 10;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  /* 允许地图交互穿透 */
}

.panel-header {
  padding: 0px 10px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8f9fa;
}

.close-btn {
  font-size: 20px;
  color: #999;

  &:hover {
    color: #666;
  }
}

.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.default-content {
  min-height: 200px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.bottom-info-bar {
  pointer-events: auto;
  /* 恢复交互能力 */
  z-index: 2002;
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 255, 255, 0.9);
  padding: 10px 20px;
  border-radius: 8px 8px 0 0;
  display: flex;
  gap: 20px;
}

.top-info-bar {
  /* pointer-events: auto;恢复交互能力 */
  z-index: 2002;
  position: fixed;
  top: 120;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 255, 255, 0.9);
  padding: 10px 20px;
  border-radius: 8px 8px 0 0;
  display: flex;
  gap: 20px;
  color: #1e00ff;
}

/* 添加工具按钮过渡效果 */
.default-toolbar button {
  transition: all 0.3s ease;
  min-width: 80px;
}

/* 工具按钮激活状态 */
.default-toolbar button.active {
  background: #1890ff;
  color: white;
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.location-input {
  z-index: 2000;
}

.location-input {
  display: flex;
  gap: 10px;
  align-items: center;
  max-width: 600px;
  /* 可选：限制最大宽度 */
  margin: 20px;
}

.location-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.location-input button {
  padding: 10px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 颜色选择器样式 */
.el-color-picker__trigger {
  width: 40px;
  height: 30px;
}

/* 弹窗样式 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 在样式部分添加 */
.icon-radius:before {
  content: "⦿";
  margin-right: 5px;
}

.info-block.radius {
  color: #0066cc;
  background: rgba(0, 102, 204, 0.1);
  padding: 8px;
  border-radius: 4px;
}

.default-toolbar button.active {
  background: #1890ff;
  color: white;
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.amap-marker>.custom-marker {
  width: 30px;
  height: 30px;
  background: url('~@/assets/image/location.png') no-repeat !important;

}

.custom-marker-active {
  background-image: url('~@/assets/image/location-icon-32.png');
}

.right-panel {
  position: fixed;
  right: 20px;
  top: 20px;
  height: 80vh;
  background: rgba(255, 255, 255, 0.98);
  box-shadow: -2px 0 12px rgba(0, 0, 0, 0.1);
  z-index: 20001;
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #ebeef5;
  pointer-events: auto;
}

.analysis-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/analysis-icon-32.png) center center no-repeat !important;
  background-size: 16px 16px;
}

.circle-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/circle-icon-32.png) center center no-repeat !important;
  background-size: 32px 32px;
}

.location-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/location-icon-32.png) center center no-repeat !important;
  background-size: 32px 32px;
}

.rectangle-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/rectangle-icon-32.png) center center no-repeat !important;
  background-size: 32px 32px;
}

.clear-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/clear-icon-32.png) center center no-repeat !important;
  background-size: 32px 32px;
}

.polygon-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/polygon-icon-32.png) center center no-repeat !important;
  background-size: 32px 32px;
}

.start-edit-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/start-edit-icon-32.png) center center no-repeat !important;
  background-size: 32px 32px;
}

.cancel-edit-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/cancel-edit-icon-32.png) center center no-repeat !important;
  background-size: 32px 32px;
}

.polyline-icon-32 {
  width: 32px;
  height: 32px;
  background: url(~@/assets/image/polyline-icon-32.png) center center no-repeat !important;
  background-size: 32px 32px;
}

.default-toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 0px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 2px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1);
}

/* 优化工具提示显示 */
.tool-item {
  position: relative;
  /* 为提示文本定位提供上下文 */
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 32px;
  cursor: pointer;
  padding: 0px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.tool-title {
  position: absolute;
  top: 100%;
  /* 将文本放在图标下方 */
  left: 50%;
  transform: translateX(-50%);
  margin-top: 8px;
  font-size: 12px;
  display: block;
  width: auto;
  min-width: 100px;
  text-align: center;
  color: #333;
  background: rgba(255, 255, 255, 0.9);
  padding: 4px 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10;
  opacity: 0;
  /* 默认隐藏 */
  visibility: hidden;
  transition: all 0.3s ease;
  white-space: nowrap;
  /* 防止文本换行 */
}

/* 悬停时显示文本 */
.tool-item:hover .tool-title {
  opacity: 1;
  visibility: visible;
}

/* 激活状态 */
.tool-item.active {
  background: #e6f7ff;
  box-shadow: 0 0 0 2px #1890ff inset;
}
</style>